package la.iok.hzsvn.lewin.movie.cloud.controller;

import la.iok.hzsvn.lewin.movie.cloud.model.PhoneCode;
import la.iok.hzsvn.lewin.movie.cloud.model.PhoneCodeParam;
import la.iok.hzsvn.lewin.movie.cloud.service.PhoneCodeService;
import la.iok.hzsvn.lewin.movie.cloud.service.UserService;
import la.iok.hzsvn.lewin.movie.core.Token;
import la.iok.hzsvn.share.response.SingleDataResponse;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("phone")
public class PhoneCodeController {

    private final PhoneCodeService phoneCodeService;
    private final UserService userService;

    public PhoneCodeController(PhoneCodeService phoneCodeService, UserService userService) {
        this.phoneCodeService = phoneCodeService;
        this.userService = userService;
    }

    /**
     * 获取手机验证码
     * @param param 请求参数
     * @return 验证码
     */
    @PostMapping("code")
    public SingleDataResponse<PhoneCode> code(@RequestHeader(required = false) Token token, @RequestBody PhoneCodeParam param){
        PhoneCode phoneCode;
        if(token != null){
            phoneCode = phoneCodeService.generateAndSavePhoneCode(userService.select(token.getUserId()),param);
        }else{
            phoneCode = phoneCodeService.generateAndSavePhoneCode(param);
        }

        // 发送短信
        phoneCodeService.sendSms(phoneCode);
        // 响应中取消验证码,从手机中获取验证码
        phoneCode.setCode(null);
        return new SingleDataResponse<>(phoneCode);
    }
}
